import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import {
  ArticleInfoServiceProxy,
  ArticleInfoEditDto,
  GetDataComboItemDtoOfInt64,
  GetEnumValuesListDto,
  CreateOrUpdateArticleInfoDto,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';

@Component({
  selector: 'create-or-edit-articleDrawer',
  templateUrl: './create-or-edit-article.component.html',
  styleUrls: ['./create-or-edit-article.component.less'],
})
export class CreateOrEditArticleComponent extends AppComponentBase {
  @Input() id?: number;
  articleForm: FormGroup;
  isLoadingBtn = false;

  article: ArticleInfoEditDto = new ArticleInfoEditDto();
  subscriptionVersion = '';
  releaseTime: string = '';

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private _articleService: ArticleInfoServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit() {
    this.articleForm = this.fb.group({
      title: [null, [Validators.required]],
      publisher: [null, [Validators.required]],
    });

    this._articleService.getArticleInfoForEdit(this.id).subscribe(result => {
      this.article = result.articleInfo;
      this.releaseTime = this.article.releaseTime === undefined ? '' : this.article.releaseTime.toString();
    });
  }

  cloumnSelectedCloumnChange(event: GetDataComboItemDtoOfInt64) {
    this.article.columnInfoId = event === undefined ? undefined : event.value;
  }

  articleSourceSelectedCloumnChange(event: GetDataComboItemDtoOfInt64) {
    this.article.articleSourceInfoId =
      event === undefined ? undefined : event.value;
  }

  typeSelectedValueChange(event: GetEnumValuesListDto) {
    this.article.recommendedType =
      event === undefined ? undefined : event.value;
  }

  close(): void {
    this.drawerRef.close(false);
  }

  submitForm() {
    for (const i in this.articleForm.controls) {
      this.articleForm.controls[i].markAsDirty();
      this.articleForm.controls[i].updateValueAndValidity();
    }
    if (this.articleForm.valid) {
      this.isLoadingBtn = true;
      const input = new CreateOrUpdateArticleInfoDto();
      input.articleInfo = this.article;
      input.articleInfo.content = '';
      console.log(this.releaseTime);
      input.articleInfo.releaseTime = moment(this.releaseTime);
      console.log(input.articleInfo);
      this._articleService
        .createOrUpdateArticleInfo(input)
        .pipe(finalize(() => (this.isLoadingBtn = false)))
        .subscribe(() => {
          this.notify.success('操作成功！');
          this.drawerRef.close(true);
        });
    }
  }
}
